import { canvasTextAutoLine } from '../../../../utils/util'
import { API_CONFIG } from '../../../../config'
import { base64src } from '../../../../utils/base64src'
const { staticUrl } = API_CONFIG
const app = getApp()
let myOptions = {}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    drawImgs: {
      qrCode: '', // 二维码
      userAvatarUrl: '', // 用户头像
      qtsheBackground: '', // 背景大图
      posterUrl: '', // 中间小图
    },
    shareImagePath: '',
    // 绘图数据
    ratio: 2,
    subTitle: '', // 副标题
    title: '', // 主标题
    defaultH: 0.6,
    defaultW: 0.7,
    windowH: 0,
    windowW: 0,
    smallWidth: 0,
    smallHeight: 0,
    appMsg: { type: 'err', show: false },

    // 逻辑数据
    activityId: "", // 活动id
    currentUserId: '', // 当前用户id
    numberId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 字符串id
    this.data.activityId = app.globalData.activityData.activityId
    // 数字id
    this.data.numberId = app.globalData.activityData.id
    myOptions = options
    this.getUserInfo().then(() => {
      this.getwxacodeunlimit(options)
    })
  },
  /**
   * @see 获取用户信息
   */
  getUserInfo () {
    return new Promise((resolve) => {
      wx.getUserInfo({
        success: (res) => {
          let { avatarUrl } = res.userInfo
          this.data.drawImgs.userAvatarUrl = avatarUrl
          resolve()
        },
        fail: err => {
          this.data.drawImgs.userAvatarUrl = 'https://xwx.gzzmedu.com:6899/pic/wx-x-mai/activity/defaultAvatar.png';
          resolve()
        }
      })
    })
  },
  /**
   * @see 生命周期,监听页面卸载
   */
  onUnload () {
    const { drawImgs } = this.data
    for (const key in drawImgs) {
      wx.removeStorage({
        key: key
      })
    }
  },
  /**
   * @see 获取小程序码
   */
  getwxacodeunlimit (options) {
    wx.showLoading({ title: '加载中..' })
    // 队长id
    const { captainId } = app.globalData.activityData
    //      字符串id      数字id
    const { activityId, numberId } = this.data
    const request = {
      captainId, // 队长id
      activityId, // 活动id(字符串)
      id: numberId // 活动id(数字)
    }
    const getElmQuery = {
      activityId,
      eIndex: [6]
    }
    console.log('获取二维码参数为:', request);
    let promiseArr = []
    promiseArr.push(wx.$API['eventConfiguration/getwxacodeunlimit'](request))
    promiseArr.push(wx.$API['eventConfiguration/getElements'](getElmQuery))
    Promise.all(promiseArr)
      .then(res => {
        // 二维码
        let qrcode = 'data:image/png;base64,' + res[0].data[0]
        let sharePoster = JSON.parse(res[1].data[0].content)
        // 海报
        let qtsheBackground = sharePoster.posterImage
        // 小图
        let posterUrl = sharePoster.shareImageX
        // 主,副标题
        let { title, subTitle } = sharePoster
        wx.hideLoading()
        // 将base64位处理成本地地址
        new Promise(resolve => {
          base64src(qrcode, res => {
            qrcode = res
            resolve()
          })
        }).then(() => {
          this.data.drawImgs.qrCode = qrcode
          this.data.drawImgs.qtsheBackground = staticUrl + qtsheBackground
          this.data.drawImgs.posterUrl = staticUrl + posterUrl
          this.data.title = title
          this.data.subTitle = subTitle
          this.init()
        })
      })
      .catch(error => {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: `${error},是否重试?`,
          success: res => {
            if (res.confirm) {
              this.getwxacodeunlimit(myOptions)
            } else if (res.cancel) {
              wx.navigateBack({
                delta: 1
              })
            }
          }
        })
        console.log('eventConfiguration/getwxacodeunlimit 获取小程序码错误!', error);
      })
  },
  /**
   * @see 初始化方法
   */
  init () {
    let systemInfo = wx.getSystemInfoSync()
    this.data.ratio = systemInfo.pixelRatio
    // 获取设备信息
    this.sys();
    // 获取图片信息
    this.getImageInfo()
  },
  /**
   * @see 用户点击右上角转发
   */
  onShareAppMessage (options) {
    // 活动id(数字) 队长id
    const { id, captainId } = app.globalData.activityData
    const param = encodeURIComponent(`u=${captainId}&a=${id}&t=1`)
    this.addData()
    return {
      title: this.data.title,
      path: `/pages/eventConfiguration/index?scene=${param}`,
      imageUrl: this.data.drawImgs.posterUrl
    }
  },
  /**
   * @see 获取图片信息
   */
  getImageInfo () {
    const { drawImgs } = this.data
    let pointerArr = []
    let httpReg = /^http/; // 图片src正则,检测是本地头像还是线上头像
    let userAvatarUrl
    // 如果是本地头像
    if (!httpReg.test(drawImgs.userAvatarUrl)) {
      // 保存
      userAvatarUrl = drawImgs.userAvatarUrl
      // 删除,不删的话在下面获取图片信息会报错
      delete drawImgs.userAvatarUrl
    }
    for (let key in drawImgs) {
      pointerArr.push(
        new Promise((resolve, reject) => {
          wx.getImageInfo({
            src: drawImgs[key],
            success: res => {
              drawImgs[key] = res.path
              resolve()
            },
            fail: err => {
              console.log(err, drawImgs[key], key, '图片信息获取失败回调')
              resolve(err)
              // this.getImageInfo()
            }
          })
        })
      )
    }
    Promise.all(pointerArr).then(() => {
      if (userAvatarUrl) { // 如果本地图片存在
        // 将本地图片放回即将绘制的对象中
        this.data.drawImgs.userAvatarUrl = userAvatarUrl
      }
      this.chooseImage()
      this.renderCanvasExport()
    }).catch(err => {
      this.chooseImage()
      this.renderCanvasExport()
      console.log(err, '报错了!')
    })
  },
  /**
   * @see 获取设备信息
   */
  sys () {
    let { defaultH, defaultW } = this.data
    wx.getSystemInfo({
      success: (res) => {
        let windowW = res.screenWidth
        let windowH = res.screenHeight
        let smallWidth = res.windowWidth * defaultW
        let smallHeight = res.windowHeight * defaultH
        this.setData({
          windowW,
          windowH,
          smallHeight,
          smallWidth,
        })
      },
    })
  },
  /**
   * @see 画图画字
   */
  canvasdraw: function (canvas, isSmall) {
    let {
      subTitle,
      title,
      smallHeight,
      smallWidth
    } = this.data
    let {
      posterUrl,
      qrCode,
      qtsheBackground,
      userAvatarUrl,
    } = this.data.drawImgs
    let windowW = this.data.windowW
    let windowH = this.data.windowH
    if (isSmall) {
      windowW = smallWidth
      windowH = smallHeight
    }
    let cy = windowH * 0.24
    let avatarPosi = windowW / 2
    let avatarSize = windowW * 0.18 / 2
    let ratio = 750 / windowW
    let fontBaseSize1 = 26
    let fontBaseSize2 = 42

    // canvas.drawImage(qtsheBackground, 0, 0, 100, 100);
    canvas.drawImage(qtsheBackground, 0, 0, windowW, windowH);
    canvas.arc(avatarPosi, cy, avatarSize, 0, 360)
    canvas.save()
    canvas.clip()
    canvas.drawImage(
      userAvatarUrl,
      avatarPosi - avatarSize,
      cy - avatarSize, avatarSize * 2,
      avatarSize * 2
    );
    canvas.restore()
    canvas.drawImage(
      posterUrl,
      windowW * 0.2,
      windowH * 0.50,
      windowW * 0.59,
      windowH * 0.24
    );
    canvas.save()
    let qrCodeX = windowW / 2
    let qrCodeY = windowH * 0.77
    let qrCodeD = 170 / ratio;
    canvas.arc(qrCodeX, qrCodeY, qrCodeD, 0, 360)
    canvas.clip()
    canvas.drawImage(qrCode, qrCodeX - qrCodeD / 2, qrCodeY, qrCodeD, qrCodeD)
    canvas.restore()
    canvas.setFontSize(fontBaseSize1 / ratio)
    canvas.textAlign = 'center';
    canvas.setStrokeStyle = '#666'
    canvas.fillText(subTitle, windowW / 2, windowH * 0.35)
    canvas.setFontSize(fontBaseSize2 / ratio)
    canvas.setStrokeStyle = '#111'
    canvasTextAutoLine(title, canvas, windowW / 2, windowH * 0.4, 60 / ratio, windowW, 400 / ratio)
    canvas.draw(true, setTimeout(() => {
    }, 1000));
    // if (!isSave) {
    wx.hideLoading()
    // }
  },
  /**
   * @see 渲染导出的canvas
   */
  renderCanvasExport () {
    let windowW = wx.getSystemInfoSync().screenWidth
    let windowH = wx.getSystemInfoSync().screenHeight
    this.setData({
      windowW,
      windowH
    }, () => {
      let canvas = wx.createCanvasContext('myCanvasExport');
      this.canvasdraw(canvas)
    })
  },
  /**
   * @see 将canvas导出为本地图片
   */
  daochu: function () {
    wx.showLoading({
      title: '生成中'
    })
    wx.getSystemInfo({
      success: (res) => {
        let windowW = res.screenWidth;
        let windowH = res.screenHeight;
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: windowW,
          height: windowH,
          destWidth: windowW,
          destHeight: windowH,
          canvasId: 'myCanvasExport',
          success: (res) => {
            this.addData()
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success (res) {
                wx.showToast({
                  title: '操作成功'
                })
              },
              fail: err => {
                wx.showToast({
                  title: '图片保存失败',
                  icon: 'none'
                })
                console.log('保存图片到系统相册失败', err)
              }
            })
            wx.previewImage({
              urls: [res.tempFilePath],
            })
          },
          fail: err => {
            wx.showModal({
              title: '保存海报失败'
            })
            console.log(err, '报错了!')
          },
          complete: () => {
            wx.hideLoading()
          }
        })
      },
    })

  },
  /**
   * @see 渲染显示canvas
   */
  chooseImage: function (isSave) {
    let canvas = wx.createCanvasContext('myCanvas');
    this.canvasdraw(canvas, true);
  },
  /**
   * @see 数据统计
   */
  addData () {
    const { activityId } = this.data
    const request = {
      activityId,
      dataType: 2
    }
    wx.$API['eventConfiguration/addData'](request).then(res => {
      console.log('数据统计 -- 分享次数加一,成功');
    })
      .catch(error => {
        console.log('数据统计 -- 分享次数加一,错误!', error);
      })
  },
})
